/*
 * Copyright (C) 2013 Daniel Treffenstädt <daniel@treffenstaedt.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include "OThreadLoop.h"

#include "OTimer.h"

O_START_NAMESPACE

ThreadLoop::ThreadLoop() :
	m_quit(false),
	m_sleep(0),
	m_ticks(0),
	m_tps(0),
	m_status(0)
{
}

void ThreadLoop::load(Object *o)
{
	m_objects.insert(o);
}

void ThreadLoop::unload(Object *o)
{
	m_objects.erase(o);
}

void ThreadLoop::run()
{
	Timer t;

	t.start();
	while (!m_quit)
	{
		for (std::unordered_set<Object*>::iterator it = m_objects.begin(); it != m_objects.end(); it++)
		{
			(*it)->callEventsD();
		}

		if (!step())
		{
			quit();
			break;
		}
		if (m_sleep > 0)
		{
			sleep(m_sleep);
		}
		m_ticks++;
		if (t.elapsed() >= 1000000)
		{
			m_tps	= m_ticks;
			m_ticks	= 0;
			t.restart();
		}
	}
}

void ThreadLoop::setMaxTicks(int max)
{
	m_sleep		= 1000 / max;
}

int ThreadLoop::getTPS()
{
	return m_tps;
}

void ThreadLoop::quit(int status)
{
	m_quit		= true;
	m_status	= status;
}

int ThreadLoop::exec()
{
	join();
	return m_status;
}

O_END_NAMESPACE
